package com.devunion.bogdan.io;

import SK.gnome.morena.MorenaSource;
import SK.gnome.morena.Morena;
import SK.gnome.morena.MorenaImage;
import SK.gnome.twain.TwainSource;

import java.awt.*;
import java.awt.image.ImageConsumer;

import com.devunion.bogdan.view.util.DialogHelper;

import javax.swing.*;

/**
 * @author Victar Liaskovich
 */
class MorenaTwainDataSource implements DataSource {

    public Image asquireImage() {
        try {
            MorenaSource source = Morena.selectSource(DialogHelper.getMainFrame());
            source.setColorMode();
            source.setResolution(100);

            if (source != null) {

                MorenaImage morenaImage = new MorenaImage(source);
                int imageStatus = morenaImage.getStatus();
                if (imageStatus == ImageConsumer.STATICIMAGEDONE) {
//                        int imageWidth = morenaImage.getWidth();
//                        int imageHeight = morenaImage.getHeight();
//                        int imagePixelSize = morenaImage.getPixelSize();

                    return Toolkit.getDefaultToolkit().createImage(morenaImage);

//                        if (TwainSource.class.isInstance(source) && ((TwainSource) source).hasMoreImages()) {
//                            continue;
//                        }

                } else if (imageStatus == ImageConsumer.IMAGEABORTED) {
                    JOptionPane.showMessageDialog(DialogHelper.getMainFrame(), "Aborted, try again ...", "Error", JOptionPane.ERROR_MESSAGE);
                } else if (imageStatus == ImageConsumer.IMAGEERROR) {
                    JOptionPane.showMessageDialog(DialogHelper.getMainFrame(), "Failed, try again ...", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(DialogHelper.getMainFrame(), "Failed, try again ...", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        catch (NoSuchMethodError error) {
            JOptionPane.showMessageDialog(DialogHelper.getMainFrame(), "Previous version of Morena is installed in " + System.getProperty("java.home") + ".\nYou have to remove it first.\nClick OK to terminate the program.", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
        catch (Throwable exception) {
            // PRESING CANCEL IN SELECT SOURCE DIALOG
            if (!(exception instanceof NullPointerException)) {
                JOptionPane.showMessageDialog(DialogHelper.getMainFrame(), exception.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                exception.printStackTrace();
            }
        }
        finally {
            try {
                Morena.close();
            }
            catch (Exception exception) {
                exception.printStackTrace();
            }
        }

        return null;
    }
}
